<?php

class NguoiDungService {

    public static function currentUser() {
        return NguoiDung::model()->findByAttributes(array('Email' => Yii::app()->user->Email));
    }

    public static function getByID($Id) {
        $user = NguoiDung::model()->findByPk($Id);
        return $user;
    }

    public static function getAll() {
        return NguoiDung::model()->findAll();
    }

    public static function getByEmail($Email) {
        $user = NguoiDung::model()->findByAttributes(array("Email" => $Email));
        return $user;
    }

    public static function getDanhMucIds($IdLinhVuc) {
        $NguoiDung = NguoiDung::model()->findByAttributes(array('Email' => Yii::app()->user->Email));
        $criteria = new CDbCriteria();
        $criteria->select = 'DanhMucId';
        $criteria->condition = 'NguoiDungId = ' . $NguoiDung->Id . ($IdLinhVuc != null ? ' and LinhVucId = ' . $IdLinhVuc : '');
        $DanhMucs = DanhMucQuanTam::model()->findAll($criteria);
        $DM = array();
        foreach ($DanhMucs as $value) {
            array_push($DM, $value->DanhMucId);
        }
        return $DM;
    }

    public static function addNguoiDung($email, $password) {
        $checkExist = NguoiDung::model()->findAllByAttributes(array("Email" => "$email"));
        if ($checkExist) {
            return FALSE;
        }
        $user = new NguoiDung();
        $user->Ten = $user->BiDanh = $user->Email = $user->TenDangNhap = $user->Ten = $email;
        $user->MatKhau = $password;
        $user->NgayDangKy = date('Y-m-d H:i:s');
        $user->save();
        return $user->Id;
    }

    public static function checkMailExist($email) {
        if (NguoiDung::model()->findByAttributes(array('Email' => $email)) != null) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public static function getListBanBe() {
        $BanBe = BanBe::model()->findAllByAttributes(array('NguoiDungId1' => Yii::app()->user->id));
        $banbes = array();
        foreach ($BanBe as $BB) {
            $nd = NguoiDung::model()->findByPk($BB->NguoiDungId2);
            array_push($banbes, $nd);
        }
        return $banbes;
    }

    public static function Follow($Id) {
        $fol = new TheoDoiNguoiDung();
        $fol->NguoiDungId1 = Yii::app()->user->id;
        $fol->NguoiDungId2 = $Id;
        return $fol->save();
    }
    
    public static function UnFollow($Id){
        $fol = TheoDoiNguoiDung::model()->findByAttributes(array('NguoiDungId1'=> Yii::app()->user->id, 'NguoiDungId2'=> $Id));
        return $fol->delete();
    }

    public static function isFollowed($Id) {
        return TheoDoiNguoiDung::model()->findByAttributes(array('NguoiDungId1' => Yii::app()->user->id, 'NguoiDungId2' => $Id)) != null;
    }

}
